package com.hbun.cxcy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hbun.cxcy.common.utils.PageUtils;
import com.hbun.cxcy.common.utils.Query;
import com.hbun.cxcy.entity.File;
import com.hbun.cxcy.entity.MacPeople;
import com.hbun.cxcy.mapper.MacPeopleMapper;
import com.hbun.cxcy.service.FileService;
import com.hbun.cxcy.service.MacPeopleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mahaunyu
 * @since 2022-01-24
 */
@Service
public class MacPeopleServiceImpl extends ServiceImpl<MacPeopleMapper, MacPeople> implements MacPeopleService {

    @Autowired
    FileService fileService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<MacPeople> wrapper = new QueryWrapper<MacPeople>()
                .eq("status",1);
        IPage<MacPeople> page = this.page(new Query<MacPeople>().getPage(params),
                wrapper);
        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveWithCustom(MacPeople macPeople) {
        macPeople.setCreateTime(new Date());
        macPeople.setUpdateTime(new Date());
        this.save(macPeople);
        // 往文件表里插入数据
        File file = new File();
        String url = macPeople.getPhotos();
        if (!StringUtils.isEmpty(url)) {
            String suffix = url.split("\\.")[1];
            String[] strings = url.split("/");
            String name = strings[strings.length - 1];
            String type = "macPeople";
            file.setType(type);
            file.setName(name);
            file.setStatus(1);
            file.setSuffix(suffix);
            file.setFilePath(url);
            file.setCreateTime(new Date());
            file.setUpdateTime(new Date());
            fileService.save(file);
        }
    }

    @Override
    public void updateByIdWithCoustom(MacPeople macPeople) {
        macPeople.setUpdateTime(new Date());
        this.updateById(macPeople);
    }

    @Override
    public void removeByIdsWithCustom(List<Long> ids) {
        for (Long id : ids) {
            MacPeople macPeople = this.baseMapper.selectById(id);
            macPeople.setStatus(0);
            this.updateById(macPeople);
        }
    }
}
